using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Threading.Tasks;
using ProductManagement.Models;
using ProductManagement.Services;

namespace ProductManagement.ViewModels
{
    public class ProductDetailViewModel : BindableBase, INavigationAware
    {
        private readonly IProductService _productService;
        private readonly IRegionManager _regionManager;
        private readonly IDialogService _dialogService;
        
        private Product _product = new();
        private string _statusMessage = "";
        private string _navigationInfo = "";
        private string _viewMode = "查看";

        public ProductDetailViewModel(IProductService productService, IRegionManager regionManager, IDialogService dialogService)
        {
            _productService = productService;
            _regionManager = regionManager;
            _dialogService = dialogService;

            // 初始化Commands
            EditCommand = new DelegateCommand(Edit);
            DeleteCommand = new DelegateCommand(async () => await DeleteAsync());
            BackToListCommand = new DelegateCommand(BackToList);
            ViewSameCategoryCommand = new DelegateCommand(ViewSameCategory);
        }

        #region Properties

        public Product Product
        {
            get { return _product; }
            set { SetProperty(ref _product, value); }
        }

        public string StatusMessage
        {
            get { return _statusMessage; }
            set { SetProperty(ref _statusMessage, value); }
        }

        public string NavigationInfo
        {
            get { return _navigationInfo; }
            set { SetProperty(ref _navigationInfo, value); }
        }

        public string ViewMode
        {
            get { return _viewMode; }
            set { SetProperty(ref _viewMode, value); }
        }

        #endregion

        #region Commands

        public DelegateCommand EditCommand { get; }
        public DelegateCommand DeleteCommand { get; }
        public DelegateCommand BackToListCommand { get; }
        public DelegateCommand ViewSameCategoryCommand { get; }

        #endregion

        #region Command Methods

        private void Edit()
        {
            var parameters = new NavigationParameters
            {
                { "ProductId", Product.Id },
                { "Mode", "Edit" }
            };
            _regionManager.RequestNavigate("ContentRegion", "AddProductView", parameters);
        }

        private async Task DeleteAsync()
        {
            var parameters = new DialogParameters
            {
                { "title", "确认删除" },
                { "message", $"您确定要删除产品 '{Product.Name}' 吗？此操作不可恢复。" }
            };

            _dialogService.ShowDialog("ConfirmationDialog", parameters, async (result) =>
            {
                if (result.Result == ButtonResult.OK)
                {
                    try
                    {
                        StatusMessage = "正在删除产品...";
                        var success = await _productService.DeleteProductAsync(Product.Id);
                        if (success)
                        {
                            StatusMessage = "产品删除成功";
                            
                            // 显示通知对话框
                            var notificationParams = new DialogParameters
                            {
                                { "title", "删除成功" },
                                { "message", "产品已成功删除，即将返回产品列表。" }
                            };
                            
                            _dialogService.ShowDialog("NotificationDialog", notificationParams, _ =>
                            {
                                _regionManager.RequestNavigate("ContentRegion", "ProductListView");
                            });
                        }
                        else
                        {
                            StatusMessage = "产品删除失败";
                        }
                    }
                    catch (Exception ex)
                    {
                        StatusMessage = $"删除产品失败: {ex.Message}";
                    }
                }
                else
                {
                    StatusMessage = "取消删除";
                }
            });
        }

        private void BackToList()
        {
            _regionManager.RequestNavigate("ContentRegion", "ProductListView");
        }

        private void ViewSameCategory()
        {
            if (!string.IsNullOrEmpty(Product.Category))
            {
                var parameters = new NavigationParameters
                {
                    { "Category", Product.Category }
                };
                _regionManager.RequestNavigate("ContentRegion", "ProductListView", parameters);
                StatusMessage = $"查看 '{Product.Category}' 分类的产品";
            }
        }

        #endregion

        #region INavigationAware

        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            try
            {
                // 获取导航参数
                if (navigationContext.Parameters.ContainsKey("ProductId"))
                {
                    var productId = navigationContext.Parameters.GetValue<int>("ProductId");
                    
                    // 获取查看模式
                    ViewMode = navigationContext.Parameters.ContainsKey("Mode") 
                        ? navigationContext.Parameters.GetValue<string>("Mode") 
                        : "查看";

                    // 构建导航信息
                    NavigationInfo = $"产品ID: {productId}\\n" +
                                   $"导航时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}\\n" +
                                   $"导航来源: {navigationContext.Uri}";

                    StatusMessage = "正在加载产品详情...";

                    // 加载产品数据
                    var product = await _productService.GetProductByIdAsync(productId);
                    if (product != null)
                    {
                        Product = product;
                        StatusMessage = "产品详情加载完成";
                    }
                    else
                    {
                        StatusMessage = "产品不存在";
                        
                        // 显示错误对话框
                        var parameters = new DialogParameters
                        {
                            { "title", "错误" },
                            { "message", "指定的产品不存在，将返回产品列表。" }
                        };
                        
                        _dialogService.ShowDialog("NotificationDialog", parameters, _ =>
                        {
                            _regionManager.RequestNavigate("ContentRegion", "ProductListView");
                        });
                    }
                }
                else
                {
                    StatusMessage = "缺少产品ID参数";
                    NavigationInfo = "导航参数错误";
                }
            }
            catch (Exception ex)
            {
                StatusMessage = $"加载产品详情失败: {ex.Message}";
            }
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            StatusMessage = "";
        }

        #endregion
    }
}